#include <iostream>
using namespace std;

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <fstream>
#include <cstring>
#include <sys/wait.h>

#define FIFONAME "./testFifo"

int main()
{
    if (access(FIFONAME, F_OK) == -1)
    {
        int ret = mkfifo(FIFONAME, 0644);
        if (ret == -1)
        {
            perror("mkfifo error");
            exit(1);
        }
    }

    /* 子进程 */
    int readFd = open(FIFONAME, O_RDONLY);
    if (readFd == -1)
    {
        perror("open fifo error");
        exit(1);
    }

    char buffer[128] = {0};
    int readBytes = 0;

    while (1)
    {
        /* 清空脏数据 */
        memset(buffer, 0, sizeof(buffer));

        readBytes = read(readFd, buffer, sizeof(buffer) - 1);
        if (readBytes < 0)
        {
            perror("read error!");
            exit(1);
        }
        if (readBytes == 0)
        {
            break;
        }
        printf("buf = %s\n", buffer);
        sleep(1);
    }

    close(readFd);
    return 0;
}